<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="json-import__wrapper">
    <div class="import-type-choose">
      <span>文件类型：</span>
      <el-select v-model="loadFileType" placeholder="请选择导入文件类型" style="width: 350px;" @change="chooseFileType">
        <el-option v-for="item in loadFileTypeList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>   
    <div v-if="loadFileType == 'EXCEL导入'" class="import-type-choose">
      <span>算法选择：</span>
      <!-- <el-select v-model="loadFileType" placeholder="请选择导入文件类型" style="width: 180px;">
        <el-option v-for="item in loadFileTypeList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select> -->
      <el-input readonly placeholder="请输入内容" v-model="algorithmConfigName" style="width: 350px;">
        <template #append>
          <el-link size="small" type="primary" @click="chooseAlgorithm">选择</el-link>
        </template>
      </el-input>
    </div>
    <el-upload 
      class="upload-demo" 
      style="width:480px;" 
      drag 
      :multiple="false"
      :limit="1"
      :file-list="uploadFiles" 
      :beforeUpload="beforeUpload" 
      :http-request="componentImport" 
      :accept="fileTypeMap[loadFileType]">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text" style="text-align: center;">
        将文件拖拽至此处或点击上传<br>
        支持上传{{loadFileType == 'EXCEL导入' ? 'excel' : (loadFileType == '压缩包导入' ? 'zip' : 'json')}}格式的文件<br>
      </div>
    </el-upload>
    <el-link v-if="loadFileType == 'Json导入' || loadFileType == '压缩包导入'" type="primary" @click="downloadTemplate">模板下载</el-link>
  </div>
  <el-dialog v-model="dialogVisible" title="算法选择" width="1200px" append-to-body :before-close="closeDialog">
    <div class="mb-[10px]">
      <el-card shadow="hover">
        <el-form ref="queryFormRef" size="small" :model="queryParams" :inline="true" label-width="120px">
          <el-form-item label="算法名称" prop="algorithmName">
            <el-input v-model="queryParams.algorithmName" placeholder="请输入算法名称" clearable />
          </el-form-item>
          <el-form-item label="实现语言" prop="algorithmLanguage">
            <el-select v-model="queryParams.algorithmLanguage" placeholder="请选择实现语言">
              <el-option v-for="item in languageList" :label="item.name" :value="item.val" :key="item.val"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否默认算法" prop="isDefault">
            <el-select v-model="queryParams.isDefault" placeholder="请选择是否默认算法">
              <el-option label="默认" :value="0"></el-option>
              <el-option label="item.name" :value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" icon="Search" @click="sureChoose">确认选择</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-table ref="tableRef" v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="算法名称" prop="algorithmName" />
      <el-table-column label="算法业务类型" prop="algorithmType" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ typeMap[scope.row.algorithmType] }}
        </template>
      </el-table-column>
      <el-table-column label="实现语言" prop="algorithmLanguage" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.algorithmLanguage }}
        </template>
      </el-table-column>
      <el-table-column label="算法描述" prop="description">
        <template #default="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column label="是否默认算法" prop="isDefault">
        <template #default="scope">   
          {{ scope.row.isDefault == '1' ? '手动新增' : '默认' }}
        </template>
      </el-table-column>
    </el-table>
    <div class="pagenation" style="display: flex; justify-content: end; padding-top: 10px;">
      <el-pagination
        v-show="total > 0"
        layout="prev, pager, next,jumper"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        v-model:current-page="queryParams.pageNum"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>

  </el-dialog>
</template>
<script setup name="TabsModel">
import { downloadFile } from '@/utils/index';
import { getModelTemplateByModelId } from '@/api/dataAcquisition';
import { 
  getAlgorithmConfigList, 
} from '@/api/algorithmConfig/index';
const uploadFiles = ref([]);
const modelId = ref('');
const loadFileType = ref('');
const dialogVisible = ref(false);
const total = ref(0);
const rowData = ref({});
const selectionList = ref([]);
const tableList = ref([]);
const tableRef = ref(null);
const loading = ref(false);
const algorithmConfigId = ref('');
const algorithmConfigName = ref('');
const loadFileTypeList = [{
  label: 'Json导入',
  value: 'Json导入'
},{
  label: 'EXCEL导入',
  value: 'EXCEL导入'
},{
  label: '压缩包导入',
  value: '压缩包导入'
}]
const fileTypeMap = {
  "Json导入": ".json",
  "EXCEL导入": ".xlsx,.xls",
  "压缩包导入": ".zip"
}
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    algorithmName: '',
    algorithmLanguage: '',
    isDefault: ''
});
const languageList = [
  {val: 'Python', name: 'Python'},
  {val: 'Javascript', name: 'Javascript'},
  // {id: 3, name: 'C++'}, 
]
const typeMap = {
  'section': '型材算法'
}
const chooseFileType = (val) => {
  if (val !== 'EXCEL导入') {
    algorithmConfigId.value = '';
    algorithmConfigName.value = '';
  } 
}
// 下载模板
const downloadTemplate = () => {
  getModelTemplateByModelId({modelId: modelId.value}).then(res => {
    // if (res) {
      downloadFile(res, `数据导入模板`, 'zip');
    // }
  })
}
const chooseAlgorithm = () => {
  dialogVisible.value = true;
  getList();
}
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val;
  getList();
};  

/**
 * 搜索按钮操作
 */
 const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
const getList = () => {
  loading.value = true;
  getAlgorithmConfigList(queryParams.value).then((res) => {
    tableList.value = res.rows;
    total.value = res.total
    loading.value = false;
  }).finally(() => {
    loading.value = false; 
  })
};
const handleSelectionChange = (val) => {
  // 表格选项发生变化
  selectionList.value = val
}
const sureChoose = () => {
  if (selectionList.value.length == 0 || selectionList.value.length > 1) {
    ElMessage.error('请选择一条数据');
    return; 
  }
  algorithmConfigId.value = selectionList.value[0].id;
  algorithmConfigName.value = selectionList.value[0].algorithmName;
  dialogVisible.value = false;
}
// 获取模型id
const handleData = (id) => {
  console.log('handleId', id)
  modelId.value = id
}
// 读取json文件
const componentImport = async (file, fileList) => {
  console.log(file, fileList)
  uploadFiles.value.push(file.file);
};
// 验证文件格式是否正确
const beforeUpload = (file) => {
  if (!loadFileType.value) {
    ElMessage.error('请选择导入文件类型');
    return false;
  }
  let isFile = fileTypeMap[loadFileType.value].indexOf(file.name.split('.')[file.name.split('.').length - 1]) > -1;
  const isLt = file.size / 1024 / 1024 < 500;
  if (!isFile) {
    ElMessage.error('导入文件格式不正确');
    return false;
  }
  // if (!isLt) {
  //   ElMessage.error(`导入文件太大，请交由系统管理员进行处理`);
  //   return false;
  // }
  //清空filelista
  uploadFiles.value = [];
  return isFile;
};
defineExpose({
  uploadFiles,
  loadFileType,
  algorithmConfigId,
  handleData
});
</script>
<style lang="scss" scoped>
.json-import__wrapper {
  display: flex;
  align-items: center;
  flex-direction: column;
  padding: 50px 0;
  .import-type-choose {
    padding-bottom: 10px;
    text-align: left;
  }
  .el-upload__text {
    font-size: 14px;
  }
}
</style>
